package com.vecspace.utils.datetime;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.ZonedDateTimeSerializer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**将LocalDateTime按照本地时区进行ISO 8601序列化。即在LocalDateTime格式化的基础上增加时区信息
 * @author wanghua
 * @createTime 2021-11-13
 */
public class LocalDateTimeISOSerializer extends JsonSerializer<LocalDateTime> {
    ZonedDateTimeSerializer zonedDateTimeSerializer = new ZonedDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"));//DateTimeFormatter.ISO_ZONED_DATE_TIME);
    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
        ZonedDateTime zonedDateTime = null;
        if(value != null){
            zonedDateTime = value.atZone(ZoneId.systemDefault());
        }
        zonedDateTimeSerializer.serialize(zonedDateTime, gen, serializers);
    }
}
